package com.example.rbac.common.handler;

import com.example.rbac.common.web.JsonData;
import com.example.rbac.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author XieLongzhen
 * @date 2018/12/15 19:47
 */
@Slf4j
public class GlobalExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        String url = httpServletRequest.getRequestURL().toString();
        ModelAndView mv;
        String defaultMsg = "System Error";

        /**
         * 要求项目中所有请求json数据，都使用.json结尾
         */
        if (url.endsWith(".json")) {
            if (e instanceof BusinessException) {
                JsonData jsonData = JsonData.fail(e.getMessage());
                mv = new ModelAndView("jsonView", jsonData.toMap());
            } else {
                log.error("unknown json exception, url: {}", url, e);
                JsonData jsonData = JsonData.fail(defaultMsg);
                mv = new ModelAndView("jsonView", jsonData.toMap());
            }
            /**
             * 要求项目中所有请求page数据，都使用.page结尾
             */
        } else if (url.endsWith(".page")) {
            log.error("unknown page exception, url: {}", url, e);
            JsonData jsonData = JsonData.fail(defaultMsg);
            mv = new ModelAndView("exception", jsonData.toMap());
        } else {
            log.error("unknown exception, url: {}", url, e);
            JsonData jsonData = JsonData.fail(defaultMsg);
            mv = new ModelAndView("jsonView", jsonData.toMap());
        }

        return mv;
    }
}
